package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.ByteUtil;
import com.firefightingiot.firefightingiot.model.DeviceBusiness;
import com.firefightingiot.firefightingiot.model.LedUploadFile;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.DeviceBusinessMapper;
import com.firefightingiot.firefightingiot.web.mapper.LedUploadFileMapper;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Yang
 */
@Service
@Slf4j
public class LEDScreenService extends BaseService {

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    LedUploadFileMapper ledUploadFileMapper;
    /**
     * 发布文字
     * @param
     * @throws
     */
    public RespEntity publishText(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String mode = "{\"name\":\"UpdateDynamic\",\"input\":{\"immediatelyPlay\":\"0\",\"cover\":\"0\",\"dynamics\":[{\"id\":\"0\",\"xCoord\":\"200\",\"yCoord\":\"500\",\"width\":\"400\",\"height\":\"400\",\"transparency\":\"100\",\"relativeProgram\":\"\",\"runMode\":\"0\",\"updateFrequency\":\"\",\"unit\":[{\"type\":\"Text\",\"order\":\"1\",\"stuntType\":\"1\",\"stuntSpeed\":\"1\",\"stayTime\":\"5\",\"content\":\"5paH5a2X\",\"bgColor\":\"0xFF000000\",\"fontSize\":\"16\",\"fontName\":\"SimSun\",\"fontSizeType\":\"1\",\"fontColor\":\"0xFFFF0000\",\"alignment\":\"0\"}]}]}}";
        JSONObject modeJson = JSONUtil.parseObj(mode);
        //屏幕设置参数
        JSONObject dynamics = (JSONObject)modeJson.getJSONObject("input").getJSONArray("dynamics").get(0);
        //坐标x
        dynamics.put("xCoord","0");
        //坐标y
        dynamics.put("yCoord","0");
        //屏幕宽度
        dynamics.put("width",jsonParam.getStr("width"));
        //坐标y
        dynamics.put("height",jsonParam.getStr("height"));
        //文字设置参数
        JSONObject unit = (JSONObject)dynamics.getJSONArray("unit").get(0);
        // 文字特技类型（见文档）
        unit.put("stuntType",jsonParam.getStr("stuntType"));
        // 特技速度
        unit.put("stuntSpeed",jsonParam.getStr("stuntSpeed"));
        // 字幕停留时间（秒）
        unit.put("stayTime",jsonParam.getStr("stayTime"));
        // 文字内容
        unit.put("content",BASE64Encoder(jsonParam.getStr("content")));
        //文字大小（单位point）
        unit.put("fontSize",jsonParam.getStr("fontSize"));
        //下发的消息序列
        String messageSequence = "0020";
        //下发指令
        jsonParam.put("code",parsingHeader(modeJson.toString(),messageSequence));
        rest(jsonParam, "ledTcpClient", "tcpClient", "tcp", "POST");
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 发布文字xml
     * @Date Created in 14:34 2021/9/17
     * @Param [jsonParam]
     */

    public RespEntity publishTextXML(JSONObject jsonParam) throws IOException, DocumentException {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String[] numbers = jsonParam.getStr("number").split(",");
        for (String number : numbers){
            jsonParam.put("number",number);
            //设备详情
            DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
            jsonParam.put("width",deviceBusiness.getLedWidth());
            jsonParam.put("height",deviceBusiness.getLedHeight());
            jsonParam.put("fontSize",deviceBusiness.getLedFontSize());
            jsonParam.put("playType","text");
            //将xml保存到本地
            java_XiuGai__XML(jsonParam);
            String mode = "{\"name\":\"downloadFileFromURL\",\"input\":{\"failonwaitingtimeout\":\"0\",\"downloadmode\":\"queue\",\"downloadtimes\":\"1\",\"updatetime\":\"0\",\"items\":[{\"srcurl\":\"http://121.89.184.226/video/C0Y1L02104190043.mp4\",\"dstpath\":\"share/\",\"dstfilename\":\"C0Y1L02104190043.mp4\",\"size\":\"6099\"}]}}";
            JSONObject modeJson = JSONUtil.parseObj(mode);
            JSONObject item = (JSONObject)modeJson.getJSONObject("input").getJSONArray("items").get(0);
            //需要下载的完整链接
            String srcurl = "http://121.89.184.226/xml/"+jsonParam.getStr("number")+"text.xml";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","programs/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+"text.xml");
            //文件大小
            item.put("size",fileSize(srcurl));
            JSONObject issuedCode = new JSONObject();
            issuedCode.put("number",number);
            //下发textXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");

            //下发list指令
            srcurl = "http://121.89.184.226/xml/"+jsonParam.getStr("number")+"list.xml";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","lists/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+"list.xml");
            //文件大小
            item.put("size",fileSize(srcurl));
            //下发listXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
        }
        return RespEntity.success();
    }
    /**
     * 屏幕截图
     * @param
     * @throws
     */
    public RespEntity screenshot(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String mode = "{\"name\":\"ScreenCapture\",\"input\":{\"suffix\":\"jpg\",\"framecount\":\"5\",\"picwidth\":\"800\",\"picheight\":\"600\"}}";
        JSONObject modeJson = JSONUtil.parseObj(mode);
        JSONObject input = modeJson.getJSONObject("input");
        //设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        //截取后图片的宽度
        input.put("picwidth",deviceBusiness.getLedWidth());
        //截取后图片的高度
        input.put("picheight",deviceBusiness.getLedHeight());
        String messageSequence = "0020";
        JSONObject issuedCode = new JSONObject();
        issuedCode.put("number",jsonParam.getStr("number"));
        //下发指令
        issuedCode.put("code",parsingHeader(modeJson.toString(),messageSequence));
        rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 播放节目
     * @Date Created in 9:31 2021/9/18
     * @Param [jsonParam]
     */

    public RespEntity play(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String mode = "{\"name\":\"play\",\"input\":{\"type\":\"program\",\"playlist\":\"lists/C0Y1L02104190043list.xml\"}}";
        JSONObject modeJson = JSONUtil.parseObj(mode);
        JSONObject input = modeJson.getJSONObject("input");
        String[] numbers = jsonParam.getStr("number").split(",");
        for (String number : numbers){
            jsonParam.put("number",number);
            //停止播放的节目类型，"program"-普通节目、"bulletin"-公告区节目、"dynamic"-所有在播动态区，还可以指定为"all"-全部节目
            //input.put("type",jsonParam.getStr("type"));
            input.put("playlist","lists/"+jsonParam.getStr("number")+"list.xml");
            //下发指令
            jsonParam.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(jsonParam, "ledTcpClient", "tcpClient", "tcp", "POST");
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 停止播放
     * @Date Created in 14:34 2021/9/16
     * @Param [jsonParam]
     */

    public RespEntity stopPlay(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String mode = "{\"name\":\"stopPlay\",\"input\":{\"type\":\"all\"}}";
        JSONObject modeJson = JSONUtil.parseObj(mode);
        JSONObject input = modeJson.getJSONObject("input");
        //停止播放的节目类型，"program"-普通节目、"bulletin"-公告区节目、"dynamic"-所有在播动态区，还可以指定为"all"-全部节目
        input.put("type",jsonParam.getStr("type"));
        String[] numbers = jsonParam.getStr("number").split(",");
        for (String number : numbers){
            jsonParam.put("number",number);
            //下发指令
            //jsonParam.put("code",parsingHeader(modeJson.toString(),messageSequence));
            // TODO 停止节目临时定为停止全部节目
            jsonParam.put("code","42584C434A000000070303012A000000000000000000000000000000002022717A206A697D4562BA2371706760702CE17820282A794E30F575203E73325439F064203E2A714C2CA27C7F");
            rest(jsonParam, "ledTcpClient", "tcpClient", "tcp", "POST");
            //下发清除无用素材指令
            jsonParam.put("code","42584C433F000000070303011F000000000000000000000000000000002023307A206A697D4562BA2361686D715215F3646E617B636D21F464706D697C023D");
            rest(jsonParam, "ledTcpClient", "tcpClient", "tcp", "POST");
        }
        return RespEntity.success();
    }

    /**
     * 发布视频
     * @param
     * @throws
     */
    public RespEntity publishVideo(JSONObject jsonParam) throws IOException, DocumentException, InterruptedException {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String[] numbers = jsonParam.getStr("number").split(",");
        for (String number : numbers){
            jsonParam.put("number",number);
            //设备详情
            DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
            jsonParam.put("width",deviceBusiness.getLedWidth());
            jsonParam.put("height",deviceBusiness.getLedHeight());
            jsonParam.put("volume",deviceBusiness.getLedVolume());
            jsonParam.put("playType","video");
            //将xml保存到本地
            java_XiuGai__XML(jsonParam);
            String mode = "{\"name\":\"downloadFileFromURL\",\"input\":{\"failonwaitingtimeout\":\"0\",\"downloadmode\":\"queue\",\"downloadtimes\":\"1\",\"updatetime\":\"0\",\"items\":[{\"srcurl\":\"http://121.89.184.226/video/C0Y1L02104190043.mp4\",\"dstpath\":\"share/\",\"dstfilename\":\"C0Y1L02104190043.mp4\",\"size\":\"6099\"}]}}";
            JSONObject modeJson = JSONUtil.parseObj(mode);
            JSONObject item = (JSONObject)modeJson.getJSONObject("input").getJSONArray("items").get(0);
            //---------------------------下发video指令--------------------------------------------------
            //需要下载的完整链接
            String srcurl = "http://121.89.184.226/video/"+jsonParam.getStr("fileName");
            //String srcurl = "http://121.89.184.226/video/"+jsonParam.getStr("number")+".mp4";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","share/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+".mp4");
            //文件大小
            item.put("size",fileSize(srcurl));
            JSONObject issuedCode = new JSONObject();
            issuedCode.put("number",number);
            //下发textXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
            //---------------------------下发videoXml指令--------------------------------------------------
            //需要下载的完整链接
            srcurl = "http://121.89.184.226/xml/"+jsonParam.getStr("number")+"video.xml";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","programs/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+"video.xml");
            //文件大小
            item.put("size",fileSize(srcurl));
            //下发textXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");

            //---------------------------下发listXml指令--------------------------------------------------
            srcurl = "http://121.89.184.226/xml/"+jsonParam.getStr("number")+"list.xml";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","lists/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+"list.xml");
            //文件大小
            item.put("size",fileSize(srcurl));
            //下发textXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
        }
        Thread.sleep(10000);
        return RespEntity.success();
    }
    /**
     * 发布图片
     * @param
     * @throws
     */
    public RespEntity publishPicture(JSONObject jsonParam) throws IOException, DocumentException, InterruptedException {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String[] numbers = jsonParam.getStr("number").split(",");
        for (String number : numbers){
            jsonParam.put("number",number);
            //设备详情
            DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
            jsonParam.put("width",deviceBusiness.getLedWidth());
            jsonParam.put("height",deviceBusiness.getLedHeight());
            jsonParam.put("volume",deviceBusiness.getLedVolume());
            jsonParam.put("playType","picture");
            //将xml保存到本地
            java_XiuGai__XML(jsonParam);
            String mode = "{\"name\":\"downloadFileFromURL\",\"input\":{\"failonwaitingtimeout\":\"0\",\"downloadmode\":\"queue\",\"downloadtimes\":\"1\",\"updatetime\":\"0\",\"items\":[{\"srcurl\":\"http://121.89.184.226/video/C0Y1L02104190043.mp4\",\"dstpath\":\"share/\",\"dstfilename\":\"C0Y1L02104190043.mp4\",\"size\":\"6099\"}]}}";
            JSONObject modeJson = JSONUtil.parseObj(mode);
            JSONObject item = (JSONObject)modeJson.getJSONObject("input").getJSONArray("items").get(0);
            //---------------------------下发video指令--------------------------------------------------
            //需要下载的完整链接
            String srcurl = "";
            //String srcurl = "http://121.89.184.226/video/"+jsonParam.getStr("number")+".mp4";
            JSONObject issuedCode = new JSONObject();
            for (Object obj : jsonParam.getJSONArray("pictures")) {
                JSONObject items = (JSONObject) obj;
                srcurl = "http://121.89.184.226/video/"+items.getStr("fileName");
                item.put("srcurl",srcurl);
                //控制器上的目标路径
                item.put("dstpath","share/");
                //目标文件名
                item.put("dstfilename",items.getStr("fileName"));
                //文件大小
                item.put("size",fileSize(srcurl));
                issuedCode.put("number",number);
                //下发textXml指令
                issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
                rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
            }
            //---------------------------下发pictureXml指令--------------------------------------------------
            //需要下载的完整链接
            srcurl = "http://121.89.184.226/xml/"+jsonParam.getStr("number")+"picture.xml";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","programs/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+"picture.xml");
            //文件大小
            item.put("size",fileSize(srcurl));
            //下发textXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
            //---------------------------下发listXml指令--------------------------------------------------
            srcurl = "http://121.89.184.226/xml/"+jsonParam.getStr("number")+"list.xml";
            item.put("srcurl",srcurl);
            //控制器上的目标路径
            item.put("dstpath","lists/");
            //目标文件名
            item.put("dstfilename",jsonParam.getStr("number")+"list.xml");
            //文件大小
            item.put("size",fileSize(srcurl));
            //下发textXml指令
            issuedCode.put("code",parsingHeader(modeJson.toString(),"0020"));
            rest(issuedCode, "ledTcpClient", "tcpClient", "tcp", "POST");
        }
        Thread.sleep(5000);
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 设备发送tcp数据中转
     * @Date Created in 15:36 2021/9/9
     * @Param [jsonParam]
     */

    public RespEntity dataRelay(JSONObject jsonParam) throws UnsupportedEncodingException, InterruptedException {
        //解密之后的数据
        JSONObject jsonData = new JSONObject();
        try {
            jsonData = instructionEncryption(jsonParam);
        }catch (Exception e){
            return RespEntity.fail("数据格式不对! erro:"+e);
        }
        //登录数据
        if (jsonData.getStr("name").equals("Login")){
            JSONObject input = jsonData.getJSONObject("input");
            jsonParam.put("number",input.getStr("barcode"));
            //更新设备连接的fd
            deviceBusinessMapper.updateLedFD(jsonParam);
            if (jsonData.getStr("pwd").equals("96")){
                jsonData.put("code","42584C4358000000070396003800000000000000000000000000000001003BDD7B226E616D65223A224C6F67696E222C226F7574707574223A7B22616374696F6E223A2261757468222C2264656C6179223A223330227D7D");
            }else if (jsonData.getStr("pwd").equals("01")){
                jsonData.put("code","42584C4358000000070301013800000000000000000000000000000001003B4B7A236F606C64233B234D6E66686F232D236E7475717475233B7A23606275686E6F233B2360747569232D2365646D6078233B233231237C7C");
            }else if (jsonData.getStr("pwd").equals("02")){
                jsonData.put("code","42584C4358000000070302013800000000000000000000000000000001003B487A594C0F0C084718186E23080E074C0E0E4D1A01040501561841594302171D06014C18184314011C4A0E0E4601090D185B18181103125F00");
            }else if (jsonData.getStr("pwd").equals("03")){
                jsonData.put("code","42584C4358000000070303013800000000000000000000000000000001003B497A206A697D4562BA234E6B6F794E62AC236D717C605534A23B792669735429EF6F203E2A715534E8232E266C754C21F92338263B20023DFD");
            }else if (jsonData.getStr("pwd").equals("04")){
                jsonData.put("code","42584C4358000000070304013800000000000000000000000000000001003B4E7AA22E417D6D263823CC2F477966262E23EF3554607D70203BFB6241737C6D6D6FA27A02717D706A23AC62447564657B23BA6213202A797F");
            }
            return RespEntity.success(jsonData);
        }
        //截图
        if (jsonData.getStr("name").equals("ScreenCapture")){
            String mode = "{\n" +
                    "\"name\": \"uploadFileToFtpServer\",\n" +
                    "\"input\": {\n" +
                    "\"host\": \"121.89.184.226\",\n" +
                    "\"port\": \"21\",\n" +
                    "\"user\": \"root\",\n" +
                    "\"password\": \"jizhi@123\",\n" +
                    "\"srcfile\": \"share/example.jpg\",\n" +
                    "\"dstfile\": \"exampledir/exampleDst.jpg\"\n" +
                    "} }";
            JSONObject modeJson = JSONUtil.parseObj(mode);
            JSONObject input = modeJson.getJSONObject("input");
            input.put("srcfile",jsonData.getJSONObject("output").getStr("filepath"));
            String messageSequence = "0020";
            //查询设备号
            DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("led_fd",jsonParam.getStr("fd")));
            String number = deviceBusiness.getNumber();
            input.put("dstfile","image/"+number+".jpg");
            jsonParam.put("number",number);
            //下发的图片上传指令
            jsonParam.put("code",parsingHeader(modeJson.toString(),messageSequence));
            System.out.println(jsonParam);
            //Thread.sleep(5000);
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    rest(jsonParam, "ledTcpClient", "tcpClient", "tcp", "POST");
                }
            }, 1000*5);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 解析XML
     * @Date Created in 16:42 2021/9/13
     * @Param []
     */

    public void java_XiuGai__XML(JSONObject jsonParam) throws DocumentException, IOException {
        /*
         * 2.java修改xml
         */
        // 创建SAXReader对象
        SAXReader sr = new SAXReader(); // 需要导入jar包:dom4j
        //文字和视频
        // 关联palyxml
        String palyxml = "";
        if (jsonParam.getStr("playType").equals("video")){
            //palyxml = this.getClass().getResource("/video.xml").getPath();
            palyxml = "/mnt/iv/xml/video.xml";
            // 获取根元素
            Document document =sr.read(palyxml);
            // 获取videopanel标签
            Element videopanel = document.getRootElement().element("videopanel");
            //修改屏幕宽度
            videopanel.attribute("w").setText(jsonParam.getStr("width"));
            //修改屏幕高度
            videopanel.attribute("h").setText(jsonParam.getStr("height"));
            // 获取videoUnit标签
            Element videoUnit = videopanel.element("videoUnit");
            //修改视频音量
            videoUnit.attribute("volume").setText(jsonParam.getStr("volume"));
            //修改视频文件路径
            videoUnit.attribute("file").setText("share/"+jsonParam.getStr("number")+".mp4");
            // 调用下面的静态方法完成xml的写出
            saveDocument(document, new File("/mnt/iv/xml/"+jsonParam.getStr("number")+"video.xml"));
            //节目文件的相对路径
            jsonParam.put("programFile","/programs/"+jsonParam.getStr("number")+"video.xml");
        }else if (jsonParam.getStr("playType").equals("text")){
            //palyxml = this.getClass().getResource("/text.xml").getPath();
            palyxml = "/mnt/iv/xml/text.xml";
            // 获取根元素
            Document document =sr.read(palyxml);
            // 获取textpanel标签
            Element textpanel = document.getRootElement().element("textpanel");
            //修改屏幕宽度
            textpanel.attribute("w").setText(jsonParam.getStr("width"));
            //修改屏幕高度
            textpanel.attribute("h").setText(jsonParam.getStr("height"));
            //修改字幕特技（特技见厂家文档）
            textpanel.attribute("stuntType").setText(jsonParam.getStr("stuntType"));
            // 获取textUnit标签
            Element textUnit = textpanel.element("textUnit");
            //修改播放的文本
            textUnit.attribute("content").setText(jsonParam.getStr("content"));
            //修改特技速度
            textUnit.attribute("stuntSpeed").setText(jsonParam.getStr("stuntSpeed"));
            //textUnit.attribute("stuntSpeed").setText("7");
            //修改停留时间（秒）
            textUnit.attribute("stayTime").setText(jsonParam.getStr("stayTime"));
            //修改文字大小
            textUnit.attribute("fontSize").setText(jsonParam.getStr("fontSize"));
            // 调用下面的静态方法完成xml的写出
            saveDocument(document, new File("/mnt/iv/xml/"+jsonParam.getStr("number")+"text.xml"));
            //节目文件的相对路径
            jsonParam.put("programFile","/programs/"+jsonParam.getStr("number")+"text.xml");
        }else if (jsonParam.getStr("playType").equals("picture")){
            //palyxml = this.getClass().getResource("/picture.xml").getPath();
            palyxml = "/mnt/iv/xml/picture.xml";
            // 获取根元素
            Document document =sr.read(palyxml);
            // 获取picturepanel标签
            Element picturepanel = document.getRootElement().element("picturepanel");
            //修改屏幕宽度
            picturepanel.attribute("w").setText(jsonParam.getStr("width"));
            //修改屏幕高度
            picturepanel.attribute("h").setText(jsonParam.getStr("height"));
            // 新建picUnit标签
            for (Object obj : jsonParam.getJSONArray("pictures")){
                JSONObject items = (JSONObject) obj;
                Element picUnit = picturepanel.addElement("picUnit");
                //图片文件路径
                picUnit.addAttribute("file","/share/"+items.getStr("fileName"));
                //图片格式
                picUnit.addAttribute("fileType","jpg");
                //特技类型索引
                picUnit.addAttribute("stuntType",jsonParam.getStr("stuntType"));
                //特技速度等级，1~16，1 为最快
                picUnit.addAttribute("stuntSpeed",jsonParam.getStr("stuntSpeed"));
                //图片停留时间，以秒为单位
                picUnit.addAttribute("stayTime",jsonParam.getStr("stayTime"));
                //播放顺序：0~127
                picUnit.addAttribute("order",items.getStr("order"));
            }
            // 调用下面的静态方法完成xml的写出
            saveDocument(document, new File("/mnt/iv/xml/"+jsonParam.getStr("number")+"picture.xml"));
            //节目文件的相对路径
            jsonParam.put("programFile","/programs/"+jsonParam.getStr("number")+"picture.xml");
        }
        // 关联listxml
        //String listxml = this.getClass().getResource("/list.xml").getPath();
        String listxml = "/mnt/iv/xml/list.xml";
        // 获取根元素
        Document document =sr.read(listxml);
        //修改屏幕宽度
        document.getRootElement().attribute("screenWidth").setText(jsonParam.getStr("width"));
        //修改屏幕高度
        document.getRootElement().attribute("screenHeight").setText(jsonParam.getStr("height"));
        // 获取program标签
        Element program = document.getRootElement().element("program");
        //播放时效开始日期 格式（yyyy-MM-dd）
        program.attribute("startDate").setText(jsonParam.getStr("startDate"));
        //播放时效结束日期 格式（yyyy-MM-dd）
        program.attribute("stopDate").setText(jsonParam.getStr("stopDate"));
        //每日播放开始时间 格式（hh:mm:ss）
        program.attribute("startTime").setText(jsonParam.getStr("startTime"));
        //播放时效结束日期 格式（hh:mm:ss）
        program.attribute("stopTime").setText(jsonParam.getStr("stopTime"));
        //节目文件的相对路径
        program.attribute("programFile").setText(jsonParam.getStr("programFile"));
        // 调用下面的静态方法完成xml的写出
        saveDocument(document, new File("/mnt/iv/xml/"+jsonParam.getStr("number")+"list.xml"));
    }


    /**
     * @Author YangYu
     * @Description 查询已上传视频的文件名
     * @Date Created in 16:10 2021/10/11
     * @Param [jsonParam]
     */

    public RespEntity getLedUploadFileList(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        jsonParam.put("homeId",homeId);
        List<LedUploadFile> ledUploadFileList = ledUploadFileMapper.getLedUploadFileList(jsonParam);
        return RespEntity.success(ledUploadFileList);
    }

    /**
     * @Author YangYu
     * @Description 删除文件
     * @Date Created in 17:10 2021/11/9
     * @Param [jsonParam]
     */

    public RespEntity delFile(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        ledUploadFileMapper.deleteById(jsonParam.getStr("id"));
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 计算文件大小
     * @Date Created in 14:55 2021/9/17
     * @Param [S]
     */
    public static String fileSize(String URL) throws IOException, DocumentException {
        int size;
        URL url = new URL(URL);
        URLConnection conn = url.openConnection();
        size = conn.getContentLength();

        if (size < 0){
            conn.getInputStream().close();
            return "Could not determine file size";
        }else{
            conn.getInputStream().close();
            return Integer.toString(size);
        }
    }

    public static void main(String[] args) throws IOException, DocumentException {

        System.out.println(fileSize("http://121.89.184.226/video/jm.jpg"));
    }
    /**
     * @Author YangYu
     * @Description 保存XML
     * @Date Created in 16:43 2021/9/13
     * @Param [document, xmlFile]
     */

    public static void saveDocument(Document document, File xmlFile) throws IOException {
        Writer osWrite = new OutputStreamWriter(new FileOutputStream(xmlFile));// 创建输出流
        OutputFormat format = OutputFormat.createPrettyPrint(); // 获取输出的指定格式
        format.setEncoding("UTF-8");// 设置编码 ，确保解析的xml为UTF-8格式
        XMLWriter writer = new XMLWriter(osWrite, format);// XMLWriter
        // 指定输出文件以及格式
        writer.write(document);// 把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)
        writer.flush();
        writer.close();
    }

    /**
     * 16进制转10进制
     * @param strHex
     * @return
     */
    public static int hex16To10(String strHex) {
        BigInteger lngNum = new BigInteger(strHex, 16);
        return lngNum.intValue();
    }

    /**
     *字符串转化成为16进制字符串
     * @param s
     * @return
     */
    public static String strTo16(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }
    /**
     * base64编码
     * @param str
     * @return
     */
    public static String BASE64Encoder(String str){
        //base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(str.getBytes());
    }

    /**
     * base64解码
     * @param str
     * @return
     */
    public static String BASE64Decoder(String str) throws IOException {
        //base64解码
        BASE64Decoder decoder = new BASE64Decoder();
        return new String(decoder.decodeBuffer(str), "UTF-8");
    }
    /**
     * params:
     * code:指令加密
     * MessageSequence:服务器发出的报文范围为 0x0000～0x7FFF,服务器发出的指令使用 0x0000～0x7FFF 中的偶数,登录包使用 0x8001，服务器回复使用 0x0001
     */
    public String parsingHeader(String code, String messageSequence){
        //用于识别报文类别
        String MAGIC = "42584C43";
        //包含头部的整个报文长度，最大 65535（暂定）
        //TODO
        String FrameLengh = "";
        //协议版本
        String ProtocolVersion = "07";
        //协议类型
        String ProtocolType = "03";
        //数据加密模式（除头部外的其他数据）：
        //0x96 - 原文传输，即不加密
        String EncryptionType = "03";
        int EncryptionTypeHex = 0x03;
        //加密种子
        String EncryptionSeed = "01";
        int EncryptionSeedHex = 0x01;
        //未加密指令部分长度，最大 65535（暂定）
        //TODO
        String TextLengh = "";
        //未加密二进制数据部分长度，最大 65535（暂定）
        String BinaryLengh = "00000000";
        //保留
        String Reserved = "0000000000000000";
        //控制卡发出的报文范围为 0x8000～0xFFFF
        //服务器发出的报文范围为 0x0000～0x7FFF
        //登录包使用 0x8001，服务器回复使用 0x0001
        //心跳包使用 0x8003～0xFFFF 中的奇数
        //服务器发出的指令使用 0x0000～0x7FFF 中的偶数，控
        //制卡回复时固定加上 0x8000
        String MessageSequence = messageSequence;
        //为指令部分和二进制数据区加密前的各字节异或值
        //TODO
        String DataChecksum = "";
        //为报文头部前 31 字节的异或值
        //TODO
        String HeaderChecksum = "";

        //计算TextLengh
        String TextLenghs = hex10To16(code.length() );
        TextLengh = TextLenghs.substring(6,8)+TextLenghs.substring(4,6)+TextLenghs.substring(2,4)+TextLenghs.substring(0,2);
        //计算DataChecksum
        DataChecksum = hex10To16(getXORValue(code)).substring(6,8);
        //计算FrameLengh
        String s = hex10To16(32 + code.length());
        FrameLengh = s.substring(6,8)+s.substring(4,6)+s.substring(2,4)+s.substring(0,2);
        //计算HeaderChecksum
        String befor31=MAGIC+FrameLengh+ProtocolVersion+ProtocolType+EncryptionType+EncryptionSeed+TextLengh+BinaryLengh+Reserved+MessageSequence+DataChecksum;
        HeaderChecksum = hex10To16(getXORValue2(befor31)).substring(6,8);
        //----------------------------------------------------
        int random = 0;
        random = EncryptionSeedHex;
        byte[] data = code.getBytes();
        byte[] Json = new byte[data.length];
        if (EncryptionTypeHex == 0x96)
        {
            Json = data;
        }
        else if (EncryptionTypeHex == 0x01)
        {
            for (int n = 0; n < data.length; n++)
            {
                Json[n] = (byte)(data[n] ^ random);
            }
        }
        else if (EncryptionTypeHex == 0x02)
        {
            for (int n = 0; n < data.length; n++)
            {
                if (n == 0)
                {
                    Json[n] = (byte)(data[n] ^ random);
                }
                else
                {
                    Json[n] = (byte)(data[n] ^ Json[n - 1]);
                }
            }
        }
        else if (EncryptionTypeHex == 0x03)
        {
            for (int n = 0; n < data.length; n++)
            {
                Json[n] = (byte)(data[n] ^ random);
                int overflow = (random >> 7) & 0x01;
                random = ((random << 1) & 0xff) | overflow;
            }
        }
        else if (EncryptionTypeHex == 0x04)
        {
            for (int n = 0; n < data.length; n++)
            {
                Json[n] = (byte)(data[n] ^ random);
                int overflow = (random << 7) & 0x80;
                random = ((random >> 1) & 0xff) | overflow;
            }
        }
        //种子01，加密方式为3
        String s2 = ByteUtil.BinaryToHexString(Json).replace(" ", "");
        //组装最后发送的数据
        String resultdData = MAGIC+FrameLengh+ProtocolVersion+ProtocolType+EncryptionType+EncryptionSeed+TextLengh+BinaryLengh+Reserved+MessageSequence+DataChecksum+HeaderChecksum+s2;
        //发送数据到client
        System.out.println("resultdData:"+resultdData);
        return resultdData;
    }
    /**
     * 指令解密
     * @return
     */
    @Test
    public static JSONObject instructionEncryption(JSONObject jsonObject) throws UnsupportedEncodingException {
        String textBox1 = jsonObject.getStr("code");
        String pwd = textBox1.substring(20, 22);
        String[] numbers =  new String[textBox1.length()/2];
        for (int i = 0; i < textBox1.length() / 2; i++)
        {
            numbers[i] = textBox1.substring(i*2,i*2+2);
        }
        byte[] array = new byte[numbers.length];
        byte[] JSON = new byte[numbers.length];
        int a=0;
        //解密后的值
        String s = "";
        for (int i = 0; i < numbers.length; i++)
        {
            String hex = numbers[i];
            array[i] = (byte)Integer.parseInt(hex,16);
        }
        byte EncryptionType = array[10];
        byte EncryptionSeed = array[11];
        int i = 0;
        for (int b = 32; b < array.length; b++) {
            JSON[i]=array[b];
            i++;
        }
        int random = 0;
        String str = "";
        random = EncryptionSeed;
        byte[] json = new byte[JSON.length];
        if (array[0] == 0x42 && array[1] == 0x58 && array[2] == 0x4c && array[3] == 0x43)
        {
            if (textBox1.substring(20,22).equals("96"))
            //if (EncryptionType == 0x1)
            {
                json = JSON;
                s = new String(JSON, "UTF-8");
                JSONObject jsonObject1 = JSONUtil.parseObj(s);
                jsonObject1.put("pwd", pwd);
                return jsonObject1;
            }
            else if (EncryptionType == 0x1)
            {
                for (int n = 0; n < JSON.length; n++)
                {
                    int jk = JSON[n] ^ EncryptionSeed;
                    json[n] = (byte)(JSON[n] ^ EncryptionSeed);
                }
                s = new String(json, "UTF-8");
                JSONObject jsonTo = JSONUtil.parseObj(s);
                jsonTo.put("pwd", pwd);
                return jsonTo;
            }
            else if (EncryptionType == 0x2)
            {
                for (int n = 0; n < JSON.length; n++)
                {
                    if (n == 0)
                    {
                        json[n] = (byte)(JSON[n] ^ EncryptionSeed);
                    }
                    else
                    {
                        json[n] = (byte)(JSON[n] ^ JSON[n - 1]);
                    }
                }
                s = new String(json, "UTF-8");
                JSONObject jsonTo = JSONUtil.parseObj(s);
                jsonTo.put("pwd", pwd);
                return jsonTo;
            }
            else if (EncryptionType == 0x3)
            {
                for (int n = 0; n < JSON.length; n++)
                {
                    json[n] = (byte)(JSON[n] ^ random);
                    int overflow = (random >> 7) & 0x01;
                    random = ((random << 1) & 0xff) | overflow;
                }
                s = new String(json, "UTF-8");
                JSONObject jsonTo = JSONUtil.parseObj(s);
                jsonTo.put("pwd", pwd);
                return jsonTo;
            }
            else if (EncryptionType == 0x4)
            {
                for (int n = 0; n < JSON.length; n++)
                {
                    json[n] = (byte)(JSON[n] ^ random);
                    int overflow = (random << 7) & 0x80;
                    random = ((random >> 1) & 0xff) | overflow;
                }
                s =  new String(json);
                JSONObject jsonTo = JSONUtil.parseObj(s);
                jsonTo.put("pwd", pwd);
                return jsonTo;
            }
        }
        JSONObject jsonTo = JSONUtil.parseObj(s);
        jsonTo.put("pwd", pwd);
        return jsonTo;
    }

    /**
     * 获取异或值，计算指令
     */
    public static int getXORValue(String source){
        int c = 0x00;
        for (int i = 0;i <source.length(); i++) {
            int ch = source.charAt(i);
            c ^= ch;
        }
        return c;
    }

    /**
     * 获取异或值，计算前31个字节
     * @param source
     * @return
     */
    public static int getXORValue2(String source){
        String[] s = new String[source.length()/2];
        int sToInt = 0;
        int a = 0;
        for (int i = 0; i < source.length(); i += 2) {
            s[a] = source.substring(i, i + 2);
            a++;
        }
        for (String str : s) {
            int s1 = hex16To10(str);
            sToInt = sToInt ^ s1;
        }
        return sToInt;
    }

    /**
     * 10进制转16进制
     * @param valueTen
     * @return
     */
    public static String hex10To16(int valueTen){
        return String.format("%08X", valueTen);
    }

}
